package cn.com.zero.common.auth.util;

import cn.com.zero.api.auth.constant.HttpHeaderConstants;
import cn.com.zero.api.auth.util.TokenUtil;
import cn.com.zero.base.exception.ErrorCodeException;
import cn.com.zero.web.util.HttpRequestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * @author liuxh
 * @version 1.0.0
 * @Description 工具类
 * @createTime 2023/4/3 14:32
 */
@Component
public class AuthUtil {
    private static TokenUtil tokenUtil;

    /**
     * 获取用户ID
     *
     * @return 用户ID
     */
    public static String getUserIdFromRequest() {
        String token = HttpRequestUtil.getHeader(HttpHeaderConstants.TOKEN_HEADER);
        if (!StringUtils.hasLength(token)) {
            throw new ErrorCodeException(-80003L); // 用户未登录
        }
        String userId = tokenUtil.getTokenSubject(token, String.class);
        if (!StringUtils.hasLength(userId)) {
            throw new ErrorCodeException(-99999L); // token解析失败
        }
        return userId;
    }


    @Autowired
    public void setTokenUtil(TokenUtil tokenUtil) {
        AuthUtil.tokenUtil = tokenUtil;
    }
}
